/**
 * 聊天室显示时间
 * @param {*} time 要处理的时间戳
 */
export function timesub(time) {
	if (time.length === 13) {
		time = time.substring(0, 11);
	}
	var date = new Date(time * 1000);
	var year = date.getFullYear();
	var mou = date.getMonth() + 1;
	var day = date.getDate();
	var hours = date.getHours();
	var minutes = date.getMinutes();
	var myDate = new Date();
	var newdate = myDate.getMonth() * 30 + myDate.getDate();
	var thisdate = mou * 30 + day;
	hours < 10 ? (hours = "0" + hours) : null;
	minutes < 10 ? (minutes = "0" + minutes) : null;
	day < 10 ? (day = "0" + day) : null;
	mou < 10 ? (mou = "0" + mou) : null;
	if (myDate.getFullYear() != year) {
		var newtime = year + "-" + mou + "-" + day + " " + hours + ":" + minutes;
	} else if (newdate - thisdate > 2) {
		var newtime = mou + "-" + day + " " + hours + ":" + minutes;
	} else if (newdate - thisdate == 2) {
		var newtime = "前天 " + hours + ":" + minutes;
	} else if (newdate - thisdate == 1) {
		var newtime = "昨天 " + hours + ":" + minutes;
	} else {
		var newtime = hours + ":" + minutes;
	}
	return newtime;
}

/**
 * str => ''
 * @param {*} data 要处理的JSON数据
 */
export function str2null(data) {
	for (let x in data) {
		if (data[x] === "") {
			// 如果是null 把直接内容转为 ''
			data[x] = null;
		} else {
			if (Array.isArray(data[x])) {
				// 是数组遍历数组 递归继续处理
				data[x] = data[x].map((z) => {
					return str2null(z);
				});
			}
			if (typeof data[x] === "object") {
				// 是json 递归继续处理
				data[x] = str2null(data[x]);
			}
		}
	}
	return data;
}

/**
 * null => ''
 * @param {*} data 要处理的JSON数据
 */
export function null2str(data) {
	for (let x in data) {
		if (data[x] === null) {
			// 如果是null 把直接内容转为 ''
			data[x] = "";
		} else {
			if (Array.isArray(data[x])) {
				// 是数组遍历数组 递归继续处理
				data[x] = data[x].map((z) => {
					return null2str(z);
				});
			}
			if (typeof data[x] === "object") {
				// 是json 递归继续处理
				data[x] = null2str(data[x]);
			}
		}
	}
	return data;
}

/**
 * 时间戳转换成日期（生日）格式
 * @param {时间戳} timestamp
 */
export function timestampToBirthday(timestamp) {
	var date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
	var Y = date.getFullYear() + "/";
	var M =
		(date.getMonth() + 1 < 10 ?
			"0" + (date.getMonth() + 1) :
			date.getMonth() + 1) + "/";
	var D = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
	return Y + M + D;
}

/**
 * 时间戳转换成日期格式
 * @param {时间戳} timestamp
 */
export function timestampToTime(timestamp) {
	var date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
	var Y = date.getFullYear() + "-";
	var M =
		(date.getMonth() + 1 < 10 ?
			"0" + (date.getMonth() + 1) :
			date.getMonth() + 1) + "-";
	var D =
		date.getMonth() + 1 < 10 ? "0" + (date.getDate() + 1) : date.getDate() + 1;
	var h = date.getHours() + ":";
	var m = date.getMinutes() + ":";
	var s = date.getSeconds();
	return Y + M + D + h + m + s;
}

/**
 * 数字转整数 如 100000 转为10万
 * @param {需要转化的数} num
 * @param {需要保留的小数位数} point
 */
export function tranNumber(num, point) {
	let numStr = num.toString();
	// 十万以内直接返回
	if (numStr.length < 6) {
		return numStr;
	}
	//大于8位数是亿
	else if (numStr.length > 8) {
		let decimal = numStr.substring(
			numStr.length - 8,
			numStr.length - 8 + point
		);
		return parseFloat(parseInt(num / 100000000) + "." + decimal) + "亿";
	}
	//大于6位数是十万 (以10W分割 10W以下全部显示)
	else if (numStr.length > 5) {
		let decimal = numStr.substring(
			numStr.length - 4,
			numStr.length - 4 + point
		);
		return parseFloat(parseInt(num / 10000) + "." + decimal) + "万";
	}
}

/**
 * 时间转为星期几
 * num: 传入需要的日期间隔数
 * time2：返回日期
 */
export function getDay(day) {
	var today = new Date();
	var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
	today.setTime(targetday_milliseconds); //注意，这行是关键代码
	var tYear = today.getFullYear();
	var tMonth = today.getMonth();
	var tDate = today.getDate();
	tMonth = doHandleMonth(tMonth + 1);
	tDate = doHandleMonth(tDate);
	return tYear + "-" + tMonth + "-" + tDate;
}

/**
 * 时间转为星期几
 * datestr: 传入日期
 * week：返回格式，支持自定义，但参数必须与formateArr里保持一致
 */
export function doHandleMonth(month) {
	var m = month;
	if (month.toString().length == 1) {
		m = "0" + month;
	}
	return m;
}

/**
 * 时间戳转化为年 月 日 时 分 秒
 * ts: 传入时间戳
 * format：返回格式，支持自定义，但参数必须与formateArr里保持一致
 */
export function tsFormatTime(timestamp, format) {
	const formatTime = (date) => {
		const year = date.getFullYear();
		const month = date.getMonth() + 1;
		const day = date.getDate();
		const hour = date.getHours();
		const minute = date.getMinutes();
		const second = date.getSeconds();

		return (
			[year, month, day].map(formatNumber).join("/") +
			"" + [hour, minute, second].map(formatNumber).join(":")
		);
	};

	const formatNumber = (n) => {
		n = n.toString();
		return n[1] ? n : "0" + n;
	};

	const formateArr = ["Y", "M", "D", "h", "m", "s"];
	let returnArr = [];

	let date = new Date(timestamp);
	let year = date.getFullYear();
	let month = date.getMonth() + 1;
	let day = date.getDate();
	let hour = date.getHours();
	let minute = date.getMinutes();
	let second = date.getSeconds();
	returnArr.push(year, month, day, hour, minute, second);

	returnArr = returnArr.map(formatNumber);

	for (var i in returnArr) {
		format = format.replace(formateArr[i], returnArr[i]);
	}
	return format;
}

// 时间戳转成日期格式
export function parseTime(time, cFormat) {
	if (arguments.length === 0) {
		return null;
	}
	const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
	let date;
	if (typeof time === "object") {
		date = time;
	} else {
		if (("" + time).length === 10) time = parseInt(time) * 1000;
		date = new Date(time);
	}
	const formatObj = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds(),
		a: date.getDay(),
	};
	const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
		let value = formatObj[key];
		// Note: getDay() returns 0 on Sunday
		if (key === "a") {
			return ["日", "一", "二", "三", "四", "五", "六"][value];
		}
		if (result.length > 0 && value < 10) {
			value = "0" + value;
		}
		return value || 0;
	});
	return time_str;
}

export function formatTime(time, option) {
	time = +time * 1000;
	const d = new Date(time);
	const now = Date.now();

	const diff = (now - d) / 1000;

	if (diff < 30) {
		return "刚刚";
	} else if (diff < 3600) {
		// less 1 hour
		return Math.ceil(diff / 60) + "分钟前";
	} else if (diff < 3600 * 24) {
		return Math.ceil(diff / 3600) + "小时前";
	} else if (diff < 3600 * 24 * 2) {
		return "1天前";
	}
	if (option) {
		return parseTime(time, option);
	} else {
		return (
			d.getMonth() + 1 + "月" + d.getDate() + "日"
			//  +
			// d.getHours() +
			// "时" +
			// d.getMinutes() +
			// "分"
		);
	}
}

// 聊天界面时间格式化
export function chatTime(timeValue) {
	var timeNew = Date.parse(new Date());
	//当前时间 
	var timeDiffer = timeNew - timeValue; 
	//与当前时间误差 var returnTime = ''; 
	if (timeDiffer <= 60000) {
		//一分钟内 
		var returnTime = '刚刚';
	} else if (timeDiffer > 60000 && timeDiffer < 3600000) {
		//1小时内 
		var returnTime = Math.floor(timeDiffer / 60000 )+ '分钟前'; 
	} else if (timeDiffer >= 3600000 && timeDiffer < 86400000 && isYestday(timeValue) === false) {
		//今日 
		var returnTime = formatDateTime(timeValue).substr(11, 5);
	} else if (timeDiffer > 3600000 && isYestday(timeValue) === true) {
		//昨天 
		var returnTime = '昨天 ' + formatDateTime(timeValue).substr(11, 5);
	} else if (timeDiffer > 86400000 && isYestday(timeValue) === false && isYear(timeValue) === true) {
		//今年 
		var returnTime = formatDateTime(timeValue).substr(5, 11);
	} else if (timeDiffer > 86400000 && isYestday(timeValue) === false && isYear(timeValue) === false) {
		//不属于今年 
		var returnTime = formatDateTime(timeValue).substr(0,10); 
	}
	return returnTime;

}
//时间戳转换日期 (yyyy-MM-dd HH:mm:ss) [chatTime]
function formatDateTime(timeValue) {
	var date = new Date(timeValue);
	var y = date.getFullYear();
	var m = date.getMonth() + 1;
	m = m < 10 ? ('0' + m) : m;
	var d = date.getDate();
	d = d < 10 ? ('0' + d) : d;
	var h = date.getHours();
	h = h < 10 ? ('0' + h) : h;
	var minute = date.getMinutes();
	var second = date.getSeconds();
	minute = minute < 10 ? ('0' + minute) : minute;
	second = second < 10 ? ('0' + second) : second;
	return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
};
//判断传入日期是否为昨天 [chatTime]
function isYestday(timeValue) {
	var date = (new Date());
	//当前时间 
	var today = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();
	//今天凌晨 
	var yestday = new Date(today - 24 * 3600 * 1000).getTime();
	return timeValue < today && yestday <= timeValue;
};
//判断传入日期是否属于今年 [chatTime]
function isYear(timeValue) {
	var takeNewYear = formatDateTime(new Date()).substr(0, 4);
	//当前时间的年份 
	var takeTimeValue = formatDateTime(timeValue).substr(0, 4);
	//传入时间的年份 
	return takeTimeValue == takeNewYear;
}


// 校验是否是手机号
export function isExternal(path) {
	return /^(https?:|mailto:|tel:)/.test(path);
}

export function debounce(func, wait, immediate) {
	let timeout, args, context, timestamp, result;

	const later = function() {
		// 据上一次触发时间间隔
		const last = +new Date() - timestamp;

		// 上次被包装函数被调用时间间隔last小于设定时间间隔wait
		if (last < wait && last > 0) {
			timeout = setTimeout(later, wait - last);
		} else {
			timeout = null;
			// 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
			if (!immediate) {
				result = func.apply(context, args);
				if (!timeout) context = args = null;
			}
		}
	};

	return function(...args) {
		context = this;
		timestamp = +new Date();
		const callNow = immediate && !timeout;
		// 如果延时不存在，重新设定延时
		if (!timeout) timeout = setTimeout(later, wait);
		if (callNow) {
			result = func.apply(context, args);
			context = args = null;
		}

		return result;
	};
}
// 判断是否为空（仅支持单个变量）
export function isBlank(value) {
	return value === "" || value === null || typeof value === "undefined";
}
// 判断正整数
export function isPositiveInteger(value) {
	const reg = /^[1-9]\d*$/;
	return reg.test(value);
}
// 判断数组是否包含重复值
export function hasDuplicateValInArray(array) {
	const hash = {};
	for (const i in array) {
		if (hash[array[i]]) {
			return true;
		} else {
			hash[array[i]] = true;
		}
	}
	return false;
}

// 深拷贝克隆String方法
export function clone(obj) {
	const result = String(obj) ? [] : {};
	for (const key in obj) {
		if (obj.hasOwnProperty(key)) {
			if (typeof obj[key] === "object") {
				result[key] = deepCopy(obj[key]); // 递归复制
			} else {
				result[key] = obj[key];
			}
		}
	}
	return result;
}

// 将图片地址生成guid格式
export function guid(addresss) {
	return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
		var r = (Math.random() * 16) | 0,
			v = c == "x" ? r : (r & 0x3) | 0x8;
		return v.toString(16);
	});
}

// 生成uuid方法
export function uuid() {
	var s = [];
	var hexDigits = "0123456789abcdef";
	for (var i = 0; i < 36; i++) {
		s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
	}
	s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
	s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
	s[8] = s[13] = s[18] = s[23] = "-";

	var uuid = s.join("");
	return uuid;
}

// 银行卡号检验
export function luhnCheck(bankno) {
	var lastNum = bankno.substr(bankno.length - 1, 1); //取出最后一位（与luhn进行比较）
	var first15Num = bankno.substr(0, bankno.length - 1); //前15或18位
	var newArr = new Array();
	for (var i = first15Num.length - 1; i > -1; i--) {
		//前15或18位倒序存进数组
		newArr.push(first15Num.substr(i, 1));
	}
	var arrJiShu = new Array(); //奇数位*2的积 <9
	var arrJiShu2 = new Array(); //奇数位*2的积 >9
	var arrOuShu = new Array(); //偶数位数组
	for (var j = 0; j < newArr.length; j++) {
		if ((j + 1) % 2 == 1) {
			//奇数位
			if (parseInt(newArr[j]) * 2 < 9) arrJiShu.push(parseInt(newArr[j]) * 2);
			else arrJiShu2.push(parseInt(newArr[j]) * 2);
		} //偶数位
		else arrOuShu.push(newArr[j]);
	}

	var jishu_child1 = new Array(); //奇数位*2 >9 的分割之后的数组个位数
	var jishu_child2 = new Array(); //奇数位*2 >9 的分割之后的数组十位数
	for (var h = 0; h < arrJiShu2.length; h++) {
		jishu_child1.push(parseInt(arrJiShu2[h]) % 10);
		jishu_child2.push(parseInt(arrJiShu2[h]) / 10);
	}

	var sumJiShu = 0; //奇数位*2 < 9 的数组之和
	var sumOuShu = 0; //偶数位数组之和
	var sumJiShuChild1 = 0; //奇数位*2 >9 的分割之后的数组个位数之和
	var sumJiShuChild2 = 0; //奇数位*2 >9 的分割之后的数组十位数之和
	var sumTotal = 0;
	for (var m = 0; m < arrJiShu.length; m++) {
		sumJiShu = sumJiShu + parseInt(arrJiShu[m]);
	}

	for (var n = 0; n < arrOuShu.length; n++) {
		sumOuShu = sumOuShu + parseInt(arrOuShu[n]);
	}

	for (var p = 0; p < jishu_child1.length; p++) {
		sumJiShuChild1 = sumJiShuChild1 + parseInt(jishu_child1[p]);
		sumJiShuChild2 = sumJiShuChild2 + parseInt(jishu_child2[p]);
	}
	//计算总和
	sumTotal =
		parseInt(sumJiShu) +
		parseInt(sumOuShu) +
		parseInt(sumJiShuChild1) +
		parseInt(sumJiShuChild2);

	//计算luhn值
	var k = parseInt(sumTotal) % 10 == 0 ? 10 : parseInt(sumTotal) % 10;
	var luhn = 10 - k;

	if (lastNum == luhn) {
		return true;
	} else {
		return false;
	}
}

// 获取N天数后日期
export function fun_date(num) {
	var date1 = new Date();

	//今天时间
	var time1 =
		date1.getFullYear() + "-" + (date1.getMonth() + 1) + "-" + date1.getDate();
	console.log(time1);
	var date2 = new Date(date1);
	date2.setDate(date1.getDate() + num);
	//num是正数表示之后的时间，num负数表示之前的时间，0表示今天
	var time2 =
		date2.getFullYear() + "-" + (date2.getMonth() + 1) + "-" + date2.getDate();
	console.log(time2);
	return time2;
}

// 是否是数字
export function isNumber(checkVal) {
	var reg = /^-?[1-9][0-9]?.?[0-9]*$/;
	return reg.test(checkVal);
}
